/*
 * Copyright (c) 2025 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
import React, { useRef, useState, useCallback } from 'react';
import { View, Text, Button, StyleSheet, ScrollView, TouchableOpacity, Dimensions, useColorScheme } from 'react-native';
import { SafeAreaView, useSafeAreaInsets } from 'react-native-safe-area-context';
import { setBreakpoints } from '@hadss/react_native_breakpoints';
import { AdaptiveSheet, SIDE_POSITION, SHEET_TYPE } from '@hadss/react-native-adaptive-sheet';
import type { AdaptiveSheetMethods, HeaderComponentProps, SideSheetPositionData, BottomSheetPositionData } from '@hadss/react-native-adaptive-sheet';


const { height: SCREEN_HEIGHT } = Dimensions.get('window');

// 调试开关：设置为 false 可以关闭所有调试日志
const ENABLE_DEBUG_LOGS = false;

// 设置自定义断点值
// 这样可以精确控制断点的像素值
// md: 600-834px, lg: 834px+
// 默认 0-599 底部 600-833 居中 834+ 侧边
setBreakpoints({
  xs: 320,
  sm: 600,
  md: 834,
  lg: 1440,
  xl: Infinity,
});

const AdaptiveSheetExample = () => {
  const insets = useSafeAreaInsets(); // 顶部安全区
  const colorScheme = useColorScheme(); // 获取系统颜色方案

  const bottomDraggableRef = useRef<AdaptiveSheetMethods>(null);
  const bottomFixedRef = useRef<AdaptiveSheetMethods>(null);
  const bottomFullScreenRef = useRef<AdaptiveSheetMethods>(null);
  const sideSheetRightWithTabRef = useRef<AdaptiveSheetMethods>(null);
  const centerSheetWithTabRef = useRef<AdaptiveSheetMethods>(null);
  const adaptiveSheetRef = useRef<AdaptiveSheetMethods>(null);
  const darkModeSheetRef = useRef<AdaptiveSheetMethods>(null);

  // 为每个弹窗创建独立的 Tab 状态
  const [sideActiveTab, setSideActiveTab] = useState(0);
  const [centerActiveTab, setCenterActiveTab] = useState(0);

  const [bottomDraggableIndex, setBottomDraggableIndex] = useState(-1);
  const [bottomFixedIndex, setBottomFixedIndex] = useState(-1);
  const [bottomFullScreenIndex, setBottomFullScreenIndex] = useState(-1);
  const [sideSheetRightWithTabIndex, setSideSheetRightWithTabIndex] = useState(-1);
  const [centerSheetWithTabIndex, setCenterSheetWithTabIndex] = useState(-1);
  const [adaptiveSheetIndex, setAdaptiveSheetIndex] = useState(-1);
  const [darkModeSheetIndex, setDarkModeSheetIndex] = useState(-1);
  // 侧边弹窗的当前宽度（用于 TabBar 自适应）
  const [sideSheetWidth, setSideSheetWidth] = useState(0);
  // 居中弹窗的尺寸
  const [centerSheetSize, setCenterSheetSize] = useState({ width: 0, height: 0 });

  // 侧边弹窗回调
  const handleSideSheetStateChange = useCallback((index: number) => {
    if (ENABLE_DEBUG_LOGS) {
      console.log('[CompleteExample] handleSideSheetStateChange:', index);
    }
    setSideSheetRightWithTabIndex(index);
    if (index === -1) {
      // 关闭时重置宽度
      setSideSheetWidth(0);
    } else {
      // 打开时设置初始宽度（根据 snapPoints 50% 计算）
      const screenWidth = Dimensions.get('window').width;
      const initialWidth = Math.round(screenWidth * 0.5); // 50% 默认宽度
      setSideSheetWidth(initialWidth);
      if (ENABLE_DEBUG_LOGS) {
        console.log('[CompleteExample] Setting initial side sheet width:', initialWidth);
      }
    }
  }, []);

  const handleSideSheetPositionChange = useCallback(
    (data: SideSheetPositionData) => {
      const newWidth = Math.round(data.visibleWidth);
      if (ENABLE_DEBUG_LOGS) {
        console.log('[CompleteExample] Width changed:', newWidth, 'previous:', sideSheetWidth);
      }
      setSideSheetWidth(newWidth);
    },
    [sideSheetWidth],
  );

  // 居中弹窗回调
  const handleCenterSheetSizeChange = useCallback((data: { width: number; height: number }) => {
    if (ENABLE_DEBUG_LOGS) {
      console.log('[CompleteExample] Center sheet size:', data);
    }
    setCenterSheetSize(data);
  }, []);

  /**
   * Dark Mode 颜色映射
   * 根据系统颜色方案返回对应的颜色值
   */
  const colors = {
    // 背景颜色
    background: colorScheme === 'dark' ? '#1c1c1e' : '#ffffff',
    secondaryBackground: colorScheme === 'dark' ? '#2c2c2e' : '#f8f9fa',

    // 文本颜色
    text: colorScheme === 'dark' ? '#ffffff' : '#333333',
    secondaryText: colorScheme === 'dark' ? '#98989d' : '#666666',

    // 边框颜色
    border: colorScheme === 'dark' ? '#38383a' : '#e0e0e0',

    // 强调色
    accent: colorScheme === 'dark' ? '#0a84ff' : '#007AFF',

    // 卡片背景
    card: colorScheme === 'dark' ? '#2c2c2e' : '#ffffff',

    // 遮罩层
    backdrop: colorScheme === 'dark' ? 'rgba(0, 0, 0, 0.8)' : 'rgba(0, 0, 0, 0.5)',
  };

  /**
   * 侧边弹窗 Tab 内容组件
   */
  const SideSheetTabContent: React.FC<{
    activeTab: number;
    sheetWidth: number;
    sheetIndex: number;
    onTabChange: (index: number) => void;
  }> = ({ activeTab, sheetWidth, sheetIndex, onTabChange }) => {
    const tabs = ['Tab 1', 'Tab 2', 'Tab 3'];
    // 计算 Tab 宽度，确保不会出现负数（最小宽度 30px，每个 Tab 至少 10px）
    const tabWidth = sheetWidth > 30 ? Math.floor(sheetWidth / 3) - 10 : undefined;

    if (ENABLE_DEBUG_LOGS) {
      console.log('[SideSheetTabContent] Rendering, sheetWidth:', sheetWidth, 'tabWidth:', tabWidth, 'activeTab:', activeTab);
    }

    return (
      <>
        <View style={styles.tabBarContainer} pointerEvents="box-none">
          {tabs.map((tab, index) => (
            <TouchableOpacity
              key={index}
              style={{
                paddingVertical: 12,
                alignItems: 'center',
                borderBottomWidth: 3,
                borderBottomColor: activeTab === index ? '#007AFF' : 'transparent',
                width: tabWidth || '33%',
                backgroundColor: activeTab === index ? '#E3F2FD' : tabWidth ? '#e0e0e0' : '#f0f0f0',
              }}
              onPress={() => {
                if (ENABLE_DEBUG_LOGS) {
                  console.log('[SideSheetTabContent] Tab onPress:', index, 'current:', activeTab);
                }
                onTabChange(index);
              }}
              activeOpacity={0.7}>
              <Text style={[styles.tabText, activeTab === index && styles.activeTabText]}>
                {tab} ({tabWidth ? `${tabWidth}px` : '33%'})
              </Text>
            </TouchableOpacity>
          ))}
        </View>
        <View style={styles.tabContent}>
          <Text style={[styles.sheetTitle, { fontSize: 24, fontWeight: 'bold', color: '#007AFF' }]}>Tab {activeTab + 1} 内容</Text>
          <Text style={[styles.sheetText, { fontSize: 18, marginTop: 16 }]}>当前激活: Tab {activeTab + 1}</Text>
          <Text style={styles.sheetText}>当前状态: {sheetIndex === -1 ? '关闭' : '打开'}</Text>
          <Text style={styles.sheetDescription}>
            {activeTab === 0 && '这是 Tab 1 的内容\n\n• 侧边弹窗\n• 可拖拽调整宽度\n• Tabs 自适应布局'}
            {activeTab === 1 && '这是 Tab 2 的内容\n\n• 不同的内容区域\n• 响应 Tab 切换\n• 测试点击功能'}
            {activeTab === 2 && '这是 Tab 3 的内容\n\n• 第三个 Tab\n• 内容独立显示\n• 验证切换正常'}
          </Text>
          <Text style={[styles.sheetText, { marginTop: 16, color: '#007AFF', fontSize: 16, fontWeight: 'bold' }]}>
            当前宽度: {Math.round(sheetWidth)}px
          </Text>
        </View>
      </>
    );
  };

  /**
   * 居中弹窗 Tab 内容组件
   */
  const CenterSheetTabContent: React.FC<{
    activeTab: number;
    onTabChange: (index: number) => void;
  }> = ({ activeTab, onTabChange }) => {
    const tabs = ['Tab 1', 'Tab 2', 'Tab 3'];

    if (ENABLE_DEBUG_LOGS) {
      console.log('[CenterSheetTabContent] Rendering, activeTab:', activeTab);
    }

    return (
      <>
        <View style={styles.tabBarContainer} pointerEvents="box-none">
          {tabs.map((tab, index) => (
            <TouchableOpacity
              key={index}
              style={[styles.tab, activeTab === index && styles.activeTab]}
              onPress={() => {
                if (ENABLE_DEBUG_LOGS) {
                  console.log('[CenterSheetTabContent] Tab onPress:', index, 'current:', activeTab);
                }
                onTabChange(index);
              }}
              activeOpacity={0.7}>
              <Text style={[styles.tabText, activeTab === index && styles.activeTabText]}>{tab}</Text>
            </TouchableOpacity>
          ))}
        </View>
        <View style={styles.sheetContent}>
          <Text style={styles.sheetTitle}>Tab {activeTab + 1} 内容</Text>
          <Text style={styles.sheetDescription}>
            {activeTab === 0 && '这是 Tab 1 的内容。\n\n• 居中弹窗\n• 带 Tab Bar\n• 可以切换不同的 Tab'}
            {activeTab === 1 && '这是 Tab 2 的内容。\n\n• 不同的内容区域\n• 响应 Tab 切换\n• 测试点击功能'}
            {activeTab === 2 && '这是 Tab 3 的内容。\n\n• 第三个 Tab\n• 内容独立显示\n• 验证切换正常'}
          </Text>
          <Text style={[styles.sheetText, { marginTop: 16, color: '#007AFF' }]}>当前激活的 Tab: {activeTab + 1}</Text>
        </View>
      </>
    );
  };

  /**
   * 自定义头部组件示例
   * 这个组件可以用于所有类型的弹窗（底部、侧边、居中）
   */
  const CustomHeader: React.FC<HeaderComponentProps> = ({
    title = 'Test',
    topInset,
    height,
    leftButton,
    rightButton,
    onLeftPress,
    onRightPress,
    titleStyle,
    containerStyle = { backgroundColor: '#f3f1f1ff' },
    closeButtonColor,
    sheetType,
  }) => {
    // 根据弹窗类型调整布局
    const titleAlignment = sheetType === 'side' ? 'center' : 'flex-start';
    const defaultCloseButtonPosition = sheetType === 'bottom' ? 'left' : 'right';

    return (
      <View
        style={[
          {
            paddingTop: topInset,
            flexDirection: 'row',
            alignItems: 'center',
            paddingHorizontal: 16,
            borderBottomWidth: 2,
            borderBottomColor: closeButtonColor,
            borderBottomLeftRadius: 8,
            borderTopLeftRadius: 8,
            borderTopRightRadius: 8,
          },
          containerStyle,
        ]}>
        {/* 左侧按钮 */}
        {defaultCloseButtonPosition === 'left' ? (
          <TouchableOpacity onPress={onLeftPress} style={{ width: 48, height: 48, justifyContent: 'center', alignItems: 'center' }} activeOpacity={0.7}>
            {leftButton || <Text style={{ fontSize: 40, color: closeButtonColor, fontWeight: '300' }}>×</Text>}
          </TouchableOpacity>
        ) : (
          leftButton && (
            <TouchableOpacity onPress={onLeftPress} style={{ width: 40, height: 40, justifyContent: 'center', alignItems: 'center' }} activeOpacity={0.7}>
              {leftButton}
            </TouchableOpacity>
          )
        )}

        {/* 标题 */}
        <View style={{ flex: 1, justifyContent: 'center', alignItems: titleAlignment, paddingHorizontal: 8 }}>
          <Text style={[{ fontSize: 18, fontWeight: 'bold', color: '#333' }, titleStyle]} numberOfLines={1}>
            {title}
          </Text>
          <Text style={{ fontSize: 12, color: '#666', marginTop: 2 }}>自定义头部 - {sheetType}</Text>
        </View>

        {/* 右侧按钮 */}
        {defaultCloseButtonPosition === 'right' ? (
          <TouchableOpacity onPress={onRightPress} style={{ width: 40, height: 40, justifyContent: 'center', alignItems: 'center' }} activeOpacity={0.7}>
            {rightButton || <Text style={{ fontSize: 28, color: closeButtonColor, fontWeight: '300' }}>×</Text>}
          </TouchableOpacity>
        ) : (
          rightButton && (
            <TouchableOpacity onPress={onRightPress} style={{ width: 40, height: 40, justifyContent: 'center', alignItems: 'center' }} activeOpacity={0.7}>
              {rightButton}
            </TouchableOpacity>
          )
        )}
      </View>
    );
  };

  const CenterHeader: React.FC<HeaderComponentProps> = ({
    title = 'Test',
    height = 52,
    leftButton,
    rightButton,
    onLeftPress = () => {
      alert('Test');
    },
    onRightPress = () => centerSheetWithTabRef.current?.close(),
    titleStyle,
    containerStyle,
    closeButtonColor = '#104985ff',
    sheetType,
  }) => {
    return (
      <View
        style={[
          {
            height: height,
            flexDirection: 'row',
            alignItems: 'center',
            paddingHorizontal: 16,
            backgroundColor: '#f8f9fa',
            borderBottomWidth: 2,
            borderBottomColor: closeButtonColor,
          },
          containerStyle,
        ]}>
        {/* 左侧按钮 */}
        <TouchableOpacity onPress={onLeftPress} style={{ width: 40, height: 40, justifyContent: 'center', alignItems: 'center' }} activeOpacity={0.7}>
          {<Text style={{ fontSize: 18, fontWeight: '300' }}>√</Text>}
        </TouchableOpacity>

        {/* 标题 */}
        <View style={{ flex: 1, justifyContent: 'center', paddingHorizontal: 8 }}>
          <Text style={[{ fontSize: 18, fontWeight: 'bold', color: '#333' }, titleStyle]} numberOfLines={1}>
            {title}
          </Text>
          <Text style={{ fontSize: 12, color: '#666', marginTop: 2 }}>自定义头部 - {sheetType}</Text>
        </View>

        {/* 右侧按钮 */}
        <TouchableOpacity onPress={onRightPress} style={{ width: 40, height: 40, justifyContent: 'center', alignItems: 'center' }} activeOpacity={0.7}>
          {<Text style={{ fontSize: 28, color: closeButtonColor, fontWeight: '300' }}>×</Text>}
        </TouchableOpacity>
      </View>
    );
  };

  const testHeader: React.FC<HeaderComponentProps> = () => {
    return <View />;
  };

  /**
   * Dark Mode 自定义头部组件
   * 根据系统颜色方案自动调整颜色
   */
  const DarkModeHeader: React.FC<HeaderComponentProps> = ({ title = 'Dark Mode Test', topInset = 0, height = 52, onLeftPress, titleStyle, containerStyle }) => {
    return (
      <View
        style={[
          {
            height: height + topInset,
            paddingTop: topInset,
            flexDirection: 'row',
            alignItems: 'center',
            paddingHorizontal: 16,
            backgroundColor: colors.secondaryBackground,
            borderBottomWidth: 1,
            borderBottomColor: colors.border,
          },
          containerStyle,
        ]}>
        {/* 左侧关闭按钮 */}
        <TouchableOpacity onPress={onLeftPress} style={{ width: 40, height: 40, justifyContent: 'center', alignItems: 'center' }} activeOpacity={0.7}>
          <Text style={{ fontSize: 28, color: colors.accent, fontWeight: '300' }}>×</Text>
        </TouchableOpacity>

        {/* 标题 */}
        <View style={{ flex: 1, justifyContent: 'center', alignItems: 'flex-start', paddingHorizontal: 8 }}>
          <Text style={[{ fontSize: 18, fontWeight: 'bold', color: colors.text }, titleStyle]} numberOfLines={1}>
            {title}
          </Text>
          <Text style={{ fontSize: 12, color: colors.secondaryText, marginTop: 2 }}>当前模式: {colorScheme === 'dark' ? '深色模式 🌙' : '浅色模式 ☀️'}</Text>
        </View>

        {/* 右侧模式指示器 */}
        <View
          style={{
            width: 40,
            height: 40,
            justifyContent: 'center',
            alignItems: 'center',
            backgroundColor: colors.accent,
            borderRadius: 20,
          }}>
          <Text style={{ fontSize: 20 }}>{colorScheme === 'dark' ? '🌙' : '☀️'}</Text>
        </View>
      </View>
    );
  };

  return (
    <SafeAreaView style={styles.container} edges={['top', 'left', 'right']}>
      <ScrollView style={styles.content}>
        <Text style={styles.title}>弹窗组件测试</Text>
        <Text style={styles.subtitle}>测试所有弹窗类型和配置选项</Text>

        {/* 1. 底部弹窗 - 可拖拽 */}
        <View style={styles.section}>
          <Text style={styles.sectionTitle}>1. 底部弹窗 - 自由拖拽</Text>
          <Text style={styles.description}>
            • 默认高度: 70% (屏幕高度的 {Math.round(SCREEN_HEIGHT * 0.7)}px){'\n'}• 可拖拽范围: 40% ~ 90%（自由拖拽）{'\n'}• 支持拖拽到33%以下关闭{'\n'}•
            当前状态: {bottomDraggableIndex === -1 ? '关闭' : '打开'}
          </Text>
          <View style={styles.buttonGroup}>
            <Button title="打开" onPress={() => bottomDraggableRef.current?.snapToIndex(0)} />
          </View>
        </View>

        {/* 2. 底部弹窗 - 不可拖拽 */}
        <View style={styles.section}>
          <Text style={styles.sectionTitle}>2. 底部弹窗 - 不可拖拽</Text>
          <Text style={styles.description}>
            • 固定高度: 70% (屏幕高度的 {Math.round(SCREEN_HEIGHT * 0.7)}px){'\n'}• 不可拖拽{'\n'}• 点击背景蒙层关闭{'\n'}• 当前状态:{' '}
            {bottomFixedIndex === -1 ? '关闭' : '打开'}
          </Text>
          <View style={styles.buttonGroup}>
            <Button title="打开" onPress={() => bottomFixedRef.current?.snapToIndex(0)} />
          </View>
        </View>

        {/* 3. 底部弹窗 - 全屏 */}
        <View style={styles.section}>
          <Text style={styles.sectionTitle}>3. 底部弹窗 - 全屏</Text>
          <Text style={styles.description}>
            • 全屏显示 (100%){'\n'}• 带固定头部{'\n'}• 不可拖拽{'\n'}• 当前状态: {bottomFullScreenIndex === -1 ? '关闭' : '打开'}
          </Text>
          <View style={styles.buttonGroup}>
            <Button title="打开" onPress={() => bottomFullScreenRef.current?.snapToIndex(0)} />
          </View>
        </View>

        {/* 4. 侧边弹窗（右侧）- 自由拖拽 */}
        <View style={styles.section}>
          <Text style={styles.sectionTitle}>4. 侧边弹窗（右侧）- 自由拖拽</Text>
          <Text style={styles.description}>
            • 默认宽度: 50%{'\n'}• 可拖拽范围: 40% ~ 85%（自由拖拽）{'\n'}• 带 Tab Bar 导航{'\n'}• 从右侧滑出{'\n'}• 当前状态:{' '}
            {sideSheetRightWithTabIndex === -1 ? '关闭' : '打开'}
          </Text>
          <View style={styles.buttonGroup}>
            <Button title="打开" onPress={() => sideSheetRightWithTabRef.current?.snapToIndex(0)} />
          </View>
        </View>

        {/* 6. 居中弹窗 - 带 Tab Bar */}
        <View style={styles.section}>
          <Text style={styles.sectionTitle}>5. 居中弹窗 - 带 Tab Bar</Text>
          <Text style={styles.description}>
            • 测试固定尺寸: 350 x 400{'\n'}• 带 Tab Bar 导航{'\n'}• 自定义按钮{'\n'}• 当前状态: {centerSheetWithTabIndex === -1 ? '关闭' : '打开'}
            {'\n'}• 当前尺寸: {centerSheetSize.width}px x {centerSheetSize.height}px
          </Text>
          <View style={styles.buttonGroup}>
            <Button title="打开" onPress={() => centerSheetWithTabRef.current?.snapToIndex(0)} />
          </View>
        </View>

        {/* 7. 自适应弹窗 */}
        <View style={styles.section}>
          <Text style={styles.sectionTitle}>6. 自适应弹窗（使用断点库）</Text>
          <Text style={styles.description}>
            • 使用 @hadss/react_native_breakpoints{'\n'}• 根据屏幕宽度自动切换类型{'\n'}• {'< 600px: 底部弹窗'}
            {'\n'}• 600-833px: 居中弹窗{'\n'}• {'>= 834px: 右侧弹窗'}
            {'\n'}• 支持自定义断点配置{'\n'}• 当前状态: {adaptiveSheetIndex === -1 ? '关闭' : '打开'}
          </Text>
          <View style={styles.buttonGroup}>
            <Button title="打开" onPress={() => adaptiveSheetRef.current?.snapToIndex(0)} />
          </View>
        </View>

        {/* 8. Dark Mode 颜色映射测试 */}
        <View style={styles.section}>
          <Text style={styles.sectionTitle}>7. Dark Mode 颜色映射测试 🌙</Text>
          <Text style={styles.description}>
            • 自动检测系统颜色方案{'\n'}• 深色模式/浅色模式自动切换{'\n'}• 自定义颜色映射{'\n'}• 全屏显示{'\n'}• 固定头部{'\n'}• 当前系统模式:{' '}
            {colorScheme === 'dark' ? '深色模式 🌙' : '浅色模式 ☀️'}
            {'\n'}• 当前状态: {darkModeSheetIndex === -1 ? '关闭' : '打开'}
          </Text>
          <View style={styles.buttonGroup}>
            <Button title="打开" onPress={() => darkModeSheetRef.current?.snapToIndex(0)} />
          </View>
        </View>
      </ScrollView>

      {/* 1. 底部弹窗 - 自由拖拽 */}
      <AdaptiveSheet
        prefertype={SHEET_TYPE.BOTTOM}
        ref={bottomDraggableRef}
        index={bottomDraggableIndex}
        onStateChange={(index:number): void => setBottomDraggableIndex(index)}
        // 底部弹窗特定配置
        bottomSheetProps={{
          snapPoints: '70%', // 新 单个值表示默认高度，可在 40%-90% 范围内自由拖拽
          enableDragToClose: true, // 拖拽到 33% 以下关闭
          enablePanDownToClose: true, // 快速下滑关闭
          enableHandlePanningGesture: true, // 是否可拖拽
          backgroundStyle: {
            backgroundColor: '#f7f1f1ff',
            borderTopLeftRadius: 8,
            borderTopRightRadius: 8,
          },
          animationConfigs: {
            duration: 250,
          },
          onSizeChange: (data:BottomSheetPositionData) => {
            if (ENABLE_DEBUG_LOGS) {
              console.log('[CompleteExample] bottom sheet size:', data);
            }
          },
        }}>
        <View style={styles.sheetContent}>
          <Text style={styles.sheetTitle}>底部弹窗 - 自由拖拽</Text>
          <Text style={styles.sheetText}>当前状态: {bottomDraggableIndex === -1 ? '关闭' : '打开'}</Text>
          <Text style={styles.sheetDescription}>
            新 API 特点：{'\n\n'}• 默认高度 70%{'\n'}• 可在 40% ~ 90% 范围内自由拖拽{'\n'}• 拖拽到任意位置都会停留（不再吸附到固定点）{'\n'}•
            超出范围自动回弹到边界{'\n'}• 拖拽到 33% 以下关闭{'\n'}• 支持快速下滑关闭{'\n'}• 拖拽手柄可见
          </Text>
          <Text style={[styles.sheetText, { marginTop: 16, color: '#007AFF' }]}>💡 试试拖拽到不同高度，比如 55%、80% 等，松手后会停留在当前位置！</Text>
        </View>
      </AdaptiveSheet>

      {/* 2. 底部弹窗 - 不可拖拽 */}
      <AdaptiveSheet
        prefertype={SHEET_TYPE.BOTTOM}
        ref={bottomFixedRef}
        index={bottomFixedIndex}
        onStateChange={(index:number): void => setBottomFixedIndex(index)}
        bottomSheetProps={{
          snapPoints: '70%',
          headerMode: 'fixed',
          headerComponent: CustomHeader,
          backgroundStyle: {
            backgroundColor: '#fcfbfbff',
            borderTopLeftRadius: 8,
            borderTopRightRadius: 8,
          },
        }}>
        <View style={styles.sheetContent}>
          <Text style={styles.sheetTitle}>底部弹窗 - 不可拖拽</Text>
          <Text style={styles.sheetText}>固定高度 70%</Text>
          <Text style={styles.sheetDescription}>
            特点：{'\n\n'}• 固定高度 70%{'\n'}• 不可拖拽{'\n'}• 点击背景蒙层关闭{'\n'}• 无拖拽手柄
          </Text>
        </View>
      </AdaptiveSheet>

      {/* 3. 底部弹窗 - 全屏（100% 不可拖拽） */}
      <AdaptiveSheet
        prefertype={SHEET_TYPE.BOTTOM}
        ref={bottomFullScreenRef}
        index={bottomFullScreenIndex}
        onStateChange={(index:number): void => setBottomFullScreenIndex(index)}
        bottomSheetProps={{
          snapPoints: '100%', // 100% 自动禁用拖拽
          headerMode: 'fixed',
          headerComponent: CustomHeader,
          topInset: insets.top,
        }}>
        <ScrollView
          style={styles.fullScreenContent}
          contentContainerStyle={{
            padding: 20,
            paddingBottom:30, 
          }}>
          <Text style={styles.sheetTitle}>全屏底部弹窗</Text>
          <Text style={styles.sheetText}>这是一个全屏显示的底部弹窗</Text>
          <Text style={styles.sheetDescription}>
            {'\n\n'}• 全屏显示 (100%){'\n'}• 设置 snapPoints="100%" 自动禁用拖拽{'\n'}• 带固定头部（自动处理顶部安全区）{'\n'}• 头部有关闭按钮
            {'\n'}• 内容可滚动{'\n'}• 底部自动处理安全区
          </Text>
          {[...Array(20)].map((_, i) => (
            <View key={i} style={styles.listItem}>
              <Text style={styles.listItemText}>列表项 {i + 1}</Text>
            </View>
          ))}
        </ScrollView>
      </AdaptiveSheet>

      {/* 4. 侧边弹窗（右侧）- 自由拖拽 */}
      <AdaptiveSheet
        prefertype={SHEET_TYPE.SIDE}
        ref={sideSheetRightWithTabRef}
        index={-1} // 初始状态为关闭
        onStateChange={handleSideSheetStateChange}
        sideSheetProps={{
          snapPoints: '50%', // 单个值表示默认宽度，可在 40%-85% 范围内自由拖拽
          position: SIDE_POSITION.RIGHT,
          enablePanToClose: true, // 快速滑动关闭
          enableDragToClose: true, // 拖拽到 33% 以下关闭
          enableHandlePanningGesture: true,
          showHeader: true,
          headerComponent: CustomHeader,
          topInset: insets.top,
          backgroundStyle: {
            backgroundColor: '#ffffff',
            borderBottomLeftRadius: 8,
            borderTopLeftRadius: 8,
          },
          onSizeChange: handleSideSheetPositionChange,
        }}>
        <View style={styles.sheetContentWithTab} key={`side-sheet-${sideActiveTab}-${Math.floor(sideSheetWidth / 10)}`}>
          <SideSheetTabContent activeTab={sideActiveTab} sheetWidth={sideSheetWidth} sheetIndex={sideSheetRightWithTabIndex} onTabChange={setSideActiveTab} />
        </View>
      </AdaptiveSheet>

      {/* 10. 居中弹窗 - 带 Tab Bar */}
      <AdaptiveSheet
        prefertype={SHEET_TYPE.CENTER}
        ref={centerSheetWithTabRef}
        index={centerSheetWithTabIndex}
        onStateChange={(index:number): void => setCenterSheetWithTabIndex(index)}
        centerSheetProps={{
          verticalMargin: 40,
          // width: 350,
          // height: 400,
          // headerComponent: testHeader,
          contentStyle: {
            // backgroundColor: '#faf4f4ff',
            // borderRadius: 8 // 设置圆角
          },
          onSizeChange: handleCenterSheetSizeChange,
        }}>
        <View key={`center-sheet-${centerActiveTab}`}>
          {/* TabBar 直接放在内容区 */}
          <CenterSheetTabContent activeTab={centerActiveTab} onTabChange={setCenterActiveTab} />
          <ScrollView
            style={styles.fullScreenContent}
            contentContainerStyle={{
              padding: 20,
              paddingBottom: 0, 
            }}>
            <Text style={styles.sheetTitle}>全屏底部弹窗</Text>
            <Text style={styles.sheetText}>这是一个全屏显示的底部弹窗</Text>
            <Text style={styles.sheetDescription}>
              新 API 特点：{'\n\n'}• 全屏显示 (100%){'\n'}• 设置 snapPoints="100%" 自动禁用拖拽{'\n'}• 带固定头部（自动处理顶部安全区）{'\n'}• 头部有关闭按钮
              {'\n'}• 内容可滚动{'\n'}• 底部自动处理安全区
            </Text>
            {[...Array(20)].map((_, i) => (
              <View key={i} style={styles.listItem}>
                <Text style={styles.listItemText}>列表项 {i + 1}</Text>
              </View>
            ))}
          </ScrollView>
        </View>
      </AdaptiveSheet>

      {/* 11. 自适应弹窗 */}
      <AdaptiveSheet
        ref={adaptiveSheetRef}
        prefertype={SHEET_TYPE.AUTO}
        index={adaptiveSheetIndex}
        title="自适应弹窗"
        onStateChange={(index:number): void => setAdaptiveSheetIndex(index)}
        bottomSheetProps={{
          snapPoints: '70%', //底部弹窗默认 70%，可在 40%-90% 范围内自由拖拽
          enablePanDownToClose: true, // 快速滑动关闭
          enableDragToClose: true, // 拖拽到 33% 以下关闭
        }}
        sideSheetProps={{
          snapPoints: '50%', //侧边弹窗默认 50%，可在 40%-85% 范围内自由拖拽
          enablePanToClose: true, // 快速滑动关闭
          enableDragToClose: true, // 拖拽到 33% 以下关闭
        }}
        centerSheetProps={{
          width: 576,
          height: 768,
          onSizeChange:(data: { width: number; height: number }) => {
            if (ENABLE_DEBUG_LOGS) {
              console.log('[Test] Center sheet size in AUTO mode:', data);
            }
          },
        }}>
        <View style={styles.sheetContent}>
          <Text style={styles.sheetTitle}>自适应弹窗</Text>
          <Text style={styles.sheetDescription}>
            这个弹窗使用 @hadss/react_native_breakpoints 库{'\n'}
            根据屏幕宽度自动切换类型：{'\n\n'}• 宽度 {'< 600px'}: 底部弹窗（70%，可自由拖拽 40%-90%）{'\n'}• 600px ≤ 宽度 {'< 834px'}: 居中弹窗{'\n'}• 宽度 ≥
            834px: 右侧弹窗（50%，可自由拖拽 40%-85%）{'\n\n'}
            尝试调整窗口大小查看效果！{'\n\n'} • 底部弹窗支持自由拖拽和拖拽关闭{'\n'}• 侧边弹窗支持自由拖拽和拖拽关闭{'\n'}• 自动适配不同屏幕尺寸
          </Text>
        </View>
      </AdaptiveSheet>

      {/* 12. Dark Mode 颜色映射测试 */}
      <AdaptiveSheet
        prefertype={SHEET_TYPE.BOTTOM}
        ref={darkModeSheetRef}
        index={darkModeSheetIndex}
        onStateChange={(index:number): void => setDarkModeSheetIndex(index)}
        bottomSheetProps={{
          snapPoints: '100%', // 全屏显示
          headerMode: 'fixed',
          headerComponent: DarkModeHeader,
          topInset: insets.top,
          backgroundStyle: {
            backgroundColor: colors.background,
          },
        }}>
        <ScrollView style={{ flex: 1, backgroundColor: colors.background }}>
          <View style={{ padding: 20 }}>
            <Text style={{ fontSize: 22, fontWeight: 'bold', marginBottom: 12, color: colors.text }}>
              Dark Mode 颜色映射测试 {colorScheme === 'dark' ? '🌙' : '☀️'}
            </Text>

            <Text style={{ fontSize: 16, marginBottom: 12, color: colors.secondaryText }}>
              当前系统颜色方案: {colorScheme === 'dark' ? '深色模式' : '浅色模式'}
            </Text>

            <Text style={{ fontSize: 14, color: colors.secondaryText, lineHeight: 22, marginBottom: 16 }}>
              这个弹窗演示了如何使用 useColorScheme Hook 自动检测系统颜色方案，并根据深色/浅色模式动态调整颜色。
            </Text>

            {/* 颜色映射展示 */}
            <Text style={{ fontSize: 18, fontWeight: 'bold', marginTop: 16, marginBottom: 12, color: colors.text }}>颜色映射表</Text>

            {/* 背景颜色 */}
            <View style={{ backgroundColor: colors.card, padding: 16, marginBottom: 8, borderRadius: 8, borderWidth: 1, borderColor: colors.border }}>
              <Text style={{ fontSize: 14, fontWeight: '600', color: colors.text, marginBottom: 4 }}>背景颜色 (background)</Text>
              <Text style={{ fontSize: 12, color: colors.secondaryText }}>浅色: #ffffff | 深色: #1c1c1e</Text>
              <View style={{ marginTop: 8, height: 40, backgroundColor: colors.background, borderRadius: 4, borderWidth: 1, borderColor: colors.border }} />
            </View>

            {/* 次要背景颜色 */}
            <View style={{ backgroundColor: colors.card, padding: 16, marginBottom: 8, borderRadius: 8, borderWidth: 1, borderColor: colors.border }}>
              <Text style={{ fontSize: 14, fontWeight: '600', color: colors.text, marginBottom: 4 }}>次要背景 (secondaryBackground)</Text>
              <Text style={{ fontSize: 12, color: colors.secondaryText }}>浅色: #f8f9fa | 深色: #2c2c2e</Text>
              <View
                style={{ marginTop: 8, height: 40, backgroundColor: colors.secondaryBackground, borderRadius: 4, borderWidth: 1, borderColor: colors.border }}
              />
            </View>

            {/* 文本颜色 */}
            <View style={{ backgroundColor: colors.card, padding: 16, marginBottom: 8, borderRadius: 8, borderWidth: 1, borderColor: colors.border }}>
              <Text style={{ fontSize: 14, fontWeight: '600', color: colors.text, marginBottom: 4 }}>文本颜色 (text)</Text>
              <Text style={{ fontSize: 12, color: colors.secondaryText }}>浅色: #333333 | 深色: #ffffff</Text>
              <View style={{ marginTop: 8, padding: 8, backgroundColor: colors.background, borderRadius: 4, borderWidth: 1, borderColor: colors.border }}>
                <Text style={{ fontSize: 16, color: colors.text }}>示例文本</Text>
              </View>
            </View>

            {/* 次要文本颜色 */}
            <View style={{ backgroundColor: colors.card, padding: 16, marginBottom: 8, borderRadius: 8, borderWidth: 1, borderColor: colors.border }}>
              <Text style={{ fontSize: 14, fontWeight: '600', color: colors.text, marginBottom: 4 }}>次要文本 (secondaryText)</Text>
              <Text style={{ fontSize: 12, color: colors.secondaryText }}>浅色: #666666 | 深色: #98989d</Text>
              <View style={{ marginTop: 8, padding: 8, backgroundColor: colors.background, borderRadius: 4, borderWidth: 1, borderColor: colors.border }}>
                <Text style={{ fontSize: 14, color: colors.secondaryText }}>示例次要文本</Text>
              </View>
            </View>

            {/* 边框颜色 */}
            <View style={{ backgroundColor: colors.card, padding: 16, marginBottom: 8, borderRadius: 8, borderWidth: 1, borderColor: colors.border }}>
              <Text style={{ fontSize: 14, fontWeight: '600', color: colors.text, marginBottom: 4 }}>边框颜色 (border)</Text>
              <Text style={{ fontSize: 12, color: colors.secondaryText }}>浅色: #e0e0e0 | 深色: #38383a</Text>
              <View style={{ marginTop: 8, height: 40, borderRadius: 4, borderWidth: 2, borderColor: colors.border }} />
            </View>

            {/* 强调色 */}
            <View style={{ backgroundColor: colors.card, padding: 16, marginBottom: 8, borderRadius: 8, borderWidth: 1, borderColor: colors.border }}>
              <Text style={{ fontSize: 14, fontWeight: '600', color: colors.text, marginBottom: 4 }}>强调色 (accent)</Text>
              <Text style={{ fontSize: 12, color: colors.secondaryText }}>浅色: #007AFF | 深色: #0a84ff</Text>
              <View style={{ marginTop: 8, height: 40, backgroundColor: colors.accent, borderRadius: 4 }} />
            </View>

            {/* 卡片背景 */}
            <View style={{ backgroundColor: colors.card, padding: 16, marginBottom: 8, borderRadius: 8, borderWidth: 1, borderColor: colors.border }}>
              <Text style={{ fontSize: 14, fontWeight: '600', color: colors.text, marginBottom: 4 }}>卡片背景 (card)</Text>
              <Text style={{ fontSize: 12, color: colors.secondaryText }}>浅色: #ffffff | 深色: #2c2c2e</Text>
              <View style={{ marginTop: 8, height: 40, backgroundColor: colors.card, borderRadius: 4, borderWidth: 1, borderColor: colors.border }} />
            </View>

            {/* 使用说明 */}
            <View
              style={{ backgroundColor: colors.secondaryBackground, padding: 16, marginTop: 16, borderRadius: 8, borderWidth: 1, borderColor: colors.border }}>
              <Text style={{ fontSize: 16, fontWeight: 'bold', color: colors.text, marginBottom: 8 }}>💡 使用说明</Text>
              <Text style={{ fontSize: 14, color: colors.secondaryText, lineHeight: 20 }}>
                1. 在 系统设置中切换深色/浅色模式{'\n'}
                2. 观察弹窗颜色的自动变化{'\n'}
                3. 所有颜色都会根据系统设置自动调整{'\n\n'}
                这个示例展示了如何使用 useColorScheme Hook 和颜色映射来实现完整的 Dark Mode 支持。
              </Text>
            </View>

            {/* 列表项示例 */}
            <Text style={{ fontSize: 18, fontWeight: 'bold', marginTop: 24, marginBottom: 12, color: colors.text }}>列表项示例</Text>
            {[...Array(5)].map((_, i) => (
              <View key={i} style={{ backgroundColor: colors.card, padding: 16, marginBottom: 8, borderRadius: 8, borderWidth: 1, borderColor: colors.border }}>
                <Text style={{ fontSize: 16, color: colors.text }}>列表项 {i + 1}</Text>
                <Text style={{ fontSize: 12, color: colors.secondaryText, marginTop: 4 }}>这是一个示例列表项，展示了 Dark Mode 下的样式</Text>
              </View>
            ))}
          </View>
        </ScrollView>
      </AdaptiveSheet>
    </SafeAreaView>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#f5f5f5',
  },
  content: {
    flex: 1,
    padding: 20,
  },
  title: {
    fontSize: 28,
    fontWeight: 'bold',
    marginBottom: 8,
    color: '#333',
  },
  subtitle: {
    fontSize: 14,
    color: '#666',
    marginBottom: 24,
  },
  section: {
    backgroundColor: '#fff',
    borderRadius: 12,
    padding: 16,
    marginBottom: 16,
    shadowColor: '#000',
    shadowOffset: { width: 0, height: 2 },
    shadowOpacity: 0.1,
    shadowRadius: 4,
    elevation: 3,
  },
  sectionTitle: {
    fontSize: 18,
    fontWeight: '600',
    marginBottom: 8,
    color: '#333',
  },
  description: {
    fontSize: 14,
    color: '#666',
    marginBottom: 12,
    lineHeight: 20,
  },
  buttonGroup: {
    flexDirection: 'row',
    justifyContent: 'center',
  },
  buttonSpacer: {
    width: 10,
  },
  // Sheet content styles
  sheetContent: {
    padding: 20,
  },
  sheetContentWithTab: {
    flex: 1,
  },
  tabContent: {
    padding: 20,
  },
  fullScreenContent: {
    flex: 1,
    padding: 20,
  },
  sheetTitle: {
    fontSize: 22,
    fontWeight: 'bold',
    marginBottom: 12,
    color: '#333',
  },
  sheetText: {
    fontSize: 16,
    marginBottom: 12,
    color: '#666',
  },
  sheetDescription: {
    fontSize: 14,
    color: '#666',
    lineHeight: 22,
    marginBottom: 16,
  },
  buttonRow: {
    flexDirection: 'row',
    justifyContent: 'space-around',
    marginTop: 8,
  },
  snapButton: {
    backgroundColor: '#007AFF',
    paddingHorizontal: 24,
    paddingVertical: 12,
    borderRadius: 8,
    minWidth: 80,
    alignItems: 'center',
  },
  snapButtonText: {
    color: '#fff',
    fontSize: 16,
    fontWeight: '600',
  },
  listItem: {
    backgroundColor: '#f8f8f8',
    padding: 16,
    marginBottom: 8,
    borderRadius: 8,
  },
  listItemText: {
    fontSize: 16,
    color: '#333',
  },
  // Tab Bar styles
  tabBarContainer: {
    flexDirection: 'row',
    paddingHorizontal: 16,
    paddingVertical: 8,
    borderBottomWidth: 1,
    borderBottomColor: '#e0e0e0',
  },
  tab: {
    flex: 1,
    paddingVertical: 8,
    alignItems: 'center',
    borderBottomWidth: 2,
    borderBottomColor: 'transparent',
  },
  activeTab: {
    borderBottomColor: '#007AFF',
  },
  tabText: {
    fontSize: 14,
    color: '#666',
  },
  activeTabText: {
    color: '#007AFF',
    fontWeight: '600',
  },
  // Custom button styles
  iconButton: {
    width: 32,
    height: 32,
    borderRadius: 16,
    backgroundColor: '#f0f0f0',
    justifyContent: 'center',
    alignItems: 'center',
  },
  iconText: {
    fontSize: 18,
    color: '#333',
  },
  rightButtonText: {
    fontSize: 16,
    color: '#007AFF',
    fontWeight: '600',
  },
  sheetScrollView: {
    flex: 1,
  },
});

export default AdaptiveSheetExample;
